from typing import Optional, List


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


"""
113. 路径总和 II
https://leetcode.cn/problems/path-sum-ii/
"""
class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        res = []

        def dfs(node, path, targetSum):
            if node == None:
                return
            if not node.left and not node.right:
                if node.val == targetSum:
                    res.append(path + [node.val])
                return
            path.append(node.val)
            dfs(node.left, path, targetSum-node.val)
            dfs(node.right, path, targetSum-node.val)
            path.pop()
            
        dfs(node=root, path=[], targetSum=targetSum)
        return res
